import { Menu, MenuProps } from 'antd';
import { bizRoutes } from '@/router/routes';
import { menuFilter } from '@/router/routes/utils.ts';
import { usePermissionRoutes, useRouter, useRouteToMenuFn } from '@/router/hooks';
import { useLocation, useMatches } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { useSiderCollapsed } from '@/store/settingsStore.ts';
import { useUserId } from '@/store/userStore.ts';
import settings from '@/router/routes/modules/settings.tsx';
import { createStyles } from 'antd-style';

const useStyle = createStyles(({ css }) => {
  return {
    menu: css`
      &.ant-menu-vertical {
        & .ant-menu-item {
          padding: 4px !important;
        }
        & .ant-menu-submenu-vertical {
          padding: 0 !important;
          & .ant-menu-submenu-title {
            padding: 4px !important;
          }
        }
      }
    `,
  };
});

const IMenu = () => {
  const { styles } = useStyle();
  const userId = useUserId();
  const permissionRoutes = usePermissionRoutes(userId === 1 ? [settings] : bizRoutes);
  const routeToMenuFn = useRouteToMenuFn();
  const items = routeToMenuFn(menuFilter(permissionRoutes));
  const router = useRouter();
  const { pathname } = useLocation();
  const matches = useMatches();
  const collapsed = useSiderCollapsed();

  const [openKeys, setOpenKeys] = useState<string[]>([]);

  useEffect(() => {
    if (collapsed) {
      setOpenKeys([]);
      return;
    }
    const openKeys = matches
      .filter((match) => match.pathname !== '/')
      .map((match) => match.pathname);
    setOpenKeys(openKeys);
  }, [matches, collapsed]);

  const onOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys);
  };

  const onClick: MenuProps['onClick'] = ({ key }) => {
    router.push(key);
  };

  return (
    <div className="flex-1 select-none overflow-auto">
      <Menu
        className={styles.menu}
        mode="inline"
        items={items}
        inlineIndent={8}
        selectedKeys={[pathname]}
        defaultSelectedKeys={[pathname]}
        openKeys={openKeys}
        defaultOpenKeys={openKeys}
        onOpenChange={onOpenChange}
        onClick={onClick}
      ></Menu>
    </div>
  );
};

export default IMenu;
